# -*- coding: utf-8 -*-
# @Time    : 2021/11/7 13:48
# @Author  : stephen
# @File    : utils.py
from django_redis import get_redis_connection
from rest_framework.permissions import BasePermission
from django.contrib.auth.models import Group
from config.dbs.redisConfig import LOGIN_KEY_TEMPLATE


class MyPermission(BasePermission):
    def has_permission(self, request, view):
        user = request.user
        # 获取有权限的分组，老师
        group = Group.objects.filter(name='老师').first()
        # 获取令牌用户所属的分组
        groups = user.groups.all()
        return user.is_superuser or group in groups


def jwt_token(token, user=None, request=None):
    """自定义登录成功返回数据处理函数"""
    param = request.data
    uuid = param.get('uuid')
    verify = param.get('verify')  # 拿到传入的验证码
    if not uuid or not verify:
        return {'msg': 'client param error'}

    # 获取保存的答案
    cache = get_redis_connection(alias='verify_codes')
    redis_verify = cache.get(LOGIN_KEY_TEMPLATE % uuid)
    if not redis_verify:
        return {'msg': 'not verify'}
    cache.delete(LOGIN_KEY_TEMPLATE % uuid)
    # 传入的验证码和答案进行比较
    if redis_verify.upper() != verify.upper():
        return {'msg': 'verify error'}

    data = {
        'token': token,
        'username': user.username
    }
    return data

